package com.sinoglobal.ningxia.activity.shop;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.vip.Login;
import com.sinoglobal.ningxia.beans.GoodsOrderInfoVo;
import com.sinoglobal.ningxia.beans.ShallShopGoodActivityVo;
import com.sinoglobal.ningxia.beans.ShallShopGoodsDataVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.AbstractActivity;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.thread.ItktAsyncTask;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.tianxia.lib.baseworld.alipay.AlixId;
import com.tianxia.lib.baseworld.alipay.BaseHelper;
import com.tianxia.lib.baseworld.alipay.MobileSecurePayHelper;
import com.tianxia.lib.baseworld.alipay.MobileSecurePayer;
import com.tianxia.lib.baseworld.alipay.ResultChecker;

import net.tsz.afinal.FinalBitmap;

/**
 * 
 * @author zbl
 * @createdate 2014-6-25 上午10:32:27
 * @Description:精品商城的现金购买时点击单个item进入此进行购买
 */
public class ShoppingCashActivity extends AbstractActivity implements OnClickListener {
	private ShallShopGoodsDataVo goodsDataVos;// 活动/商品
	private ImageView shoppingImg;// 活动的img
	private TextView mallShopGoodsName;// 活动名称
	private TextView mallShopGoodsDate;// 活动的有效期
	private TextView goodsContent;// 活动的详细介绍
	private Button goodsCode;// 购买
	private Intent intent;
	private String goodsId;
	private String orderInfor;// 现金购买活动卷是的订单信息
	private String cashCode;// 现金兑换的活动码
	private ProgressDialog progress = null;
	private final String REAL_OBJECT_TYPE = "1";//实物

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isTemplate = true;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mallshop_shopping_cash);
		titleView.setText(R.string.shoping_goodsName);
		// 获取商品的ID
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		goodsId = bundle.getString("goods_id");

		init();// 初始化控件
		loadInfo();// 从网络获取数据

	}

	// 801
	private void loadInfo() {
		new ItktAsyncTaskWithDialog<Void, Void, ShallShopGoodActivityVo>(getString(R.string.loading), true, true) {

			@Override
			public ShallShopGoodActivityVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getGoodActivityVo(REAL_OBJECT_TYPE, goodsId);
			}

			@Override
			public void after(ShallShopGoodActivityVo result) {
				if (result != null) {
					if (Code.CODE_SUCCESS != result.getCode()) {
						Toast.makeText(FlyApplication.context, result.getMessage(), Toast.LENGTH_SHORT).show();
					} else {
						// 从服务器上获取数据填充在布局文件上
						goodsDataVos = result.getEnentsDataVo();

						FinalBitmap fb = FinalBitmap.create(ShoppingCashActivity.this);
						fb.configLoadfailImage(R.drawable.default21);
						fb.configLoadingImage(R.drawable.default21);
						String URL = ConnectionUtil.localUrl + goodsDataVos.getGoods_img();
						fb.display(shoppingImg, URL);
						// 设置图片的宽高
						mallShopGoodsName.setText(goodsDataVos.getGoods_name());
						// 对于有效日期经行处理
						mallShopGoodsDate.setText(goodsDataVos.getGoods_start() + "至" + goodsDataVos.getGoods_end());
						mallShopGoodsDate.requestFocus();// 需要焦点
						goodsContent.setText(goodsDataVos.getConten());

					}
				}

			}

			@Override
			public void exception() {

			}
		}.execute();
	}

	public void init() {
		shoppingImg = (ImageView) findViewById(R.id.shopping_img);
		int width = FlyApplication.widthPixels;
		int height = width / 2;
		shoppingImg.setLayoutParams(new LinearLayout.LayoutParams(width, height));
		mallShopGoodsName = (TextView) findViewById(R.id.mallshop_goodsName);
		mallShopGoodsDate = (TextView) findViewById(R.id.mallshop_goods_date);
		goodsContent = (TextView) findViewById(R.id.goods_content);
		goodsCode = (Button) findViewById(R.id.goods_code);
		goodsCode.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.goods_code:// 点击进入购买页
			// 判断是用户是否登录
			if (TextUtil.stringIsNotNull(FlyApplication.userId)) {
				// 判断是实体物品还是活动，实物就转到填写个人信息页，活动的话返回一个活动码
				if (REAL_OBJECT_TYPE.equals(goodsDataVos.getType2())) {
					intent = new Intent(this, PurchaseGoodsActivity.class);
					intent.putExtra("goodsDataVos", goodsDataVos);
					intent.putExtra("goods_id", goodsId);// 商品的id
					intent.putExtra("type", goodsDataVos.getType());// 1现金 2积分
					intent.putExtra("type2", goodsDataVos.getType2());// 1实物 2活动
					startActivity(intent);
					finish();
				} else {
					// 访问网络获取活动码802
					new ItktAsyncTask<Void, Void, GoodsOrderInfoVo>() {
						@Override
						public GoodsOrderInfoVo before(Void... params) throws Exception {
							return RemoteImpl.getInstance().getGoodsOrderInfoVo(goodsDataVos.getType(), goodsDataVos.getType2(), goodsId);
						}

						@Override
						public void after(GoodsOrderInfoVo result) {
							if (result != null) {
								orderInfor = result.getOrderInfor();
								cashCode = result.getGoods_code();
								performPay();

							}
						}

						@Override
						public void exception() {

						}

					}.execute();

				}

			} else {
				intent = new Intent(this, Login.class);
				startActivityForResult(intent, 0);
			}
			break;
		}
	}

	private void performPay() {
		// check to see if the MobileSecurePay is already installed.
		// 检测安全支付服务是否安装
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		boolean isMobile_spExist = mspHelper.detectMobile_sp();
		if (!isMobile_spExist) {
			return;
		}

		// start pay for this order.
		// 根据订单信息开始进行支付
		try {
			String info = orderInfor;
			// start the pay.
			// 调用pay方法进行支付
			MobileSecurePayer msp = new MobileSecurePayer();

			boolean bRet = msp.pay(info, mHandler, AlixId.RQF_PAY, this);

			if (bRet) {
				// show the progress bar to indicate that we have started
				// paying.
				// 显示“正在支付”进度条
				closeProgress();
				progress = BaseHelper.showProgress(this, null, getString(R.string.paying), false, true);
			} else
				;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// close the progress bar
	// 关闭进度框
	void closeProgress() {
		try {
			if (progress != null) {
				progress.dismiss();
				progress = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//
	// the handler use to receive the pay result.
	// 这里接收支付结果，支付宝手机端同步通知
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				String ret = (String) msg.obj;
				switch (msg.what) {
				case AlixId.RQF_PAY: {
					closeProgress();
					// 处理交易结果
					try {
						// 获取交易状态码，具体状态代码请参看文档
						String tradeStatus = "resultStatus={";
						int imemoStart = ret.indexOf("resultStatus=");
						imemoStart += tradeStatus.length();
						int imemoEnd = ret.indexOf("};memo=");
						tradeStatus = ret.substring(imemoStart, imemoEnd);

						// 先验签通知
						ResultChecker resultChecker = new ResultChecker(ret);
						int retVal = resultChecker.checkSign();
						// 验签失败
						if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
							BaseHelper.showDialog(ShoppingCashActivity.this, getString(R.string.prompt_str),
									getResources().getString(R.string.check_sign_failed), android.R.drawable.ic_dialog_alert);
						} else {// 验签成功。验签成功后再判断交易状态码
							if (tradeStatus.equals("9000"))//
							// 判断交易状态码，只有9000表示交易成功
							{
								BaseHelper.showDialog(ShoppingCashActivity.this, getString(R.string.prompt_str),
										getString(R.string.pay_success), R.drawable.infoicon);
								goodsCode.setText(cashCode);
								goodsCode.setBackgroundResource(R.drawable.bg_enentitem_btn);
								goodsCode.setClickable(false);

							} else {
								BaseHelper.showDialog(ShoppingCashActivity.this, getString(R.string.prompt_str),
										getString(R.string.pay_fail), R.drawable.infoicon);
							}
						}

					} catch (Exception e) {
						e.printStackTrace();
						BaseHelper.showDialog(ShoppingCashActivity.this, getString(R.string.prompt_str), ret, R.drawable.infoicon);
					}
				}
					break;
				}

				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

}
